'''
filename: biddingService
author: yinwenlu
datetime: 2020/1/8 14:58
software: PyCharm
'''
import datetime

from db import Session, ShopMeituanInfo, ShopEleInfo
from web.service.overData.sql_db import getBiddingDateFromOpet, getHeadInfoData, getBusinessInfo

def getDate(shopid):
    # 获取这个店铺所有的操作记录
    opet_daily = getBiddingDateFromOpet(shopid)
    for op_da in opet_daily:
        op_da = op_da.to_dict()
        params = eval(op_da.get("params"))
        status2 = int(params.get("status2"))
        status3 = int(params.get("status3"))
        status4 = int(params.get("status4"))
        if status2 == 1 and status3 == 0 and status4 == 0:
            date = op_da.get("day")
            return date

#求取一元钱多少曝光，一个访客多少钱函数
def getAvgByList(l_list):
    """
    获取列表中各项数据的平均值，以及比值
    :param l_list:
    :return:
    """
    lenth = len(l_list)
    all_cost = 0
    all_exposureNum = 0
    all_clickNum = 0
    for l in l_list:
        all_cost += float(l.get("cost"))
        all_exposureNum += float(l.get("exposureNum"))
        all_clickNum += float(l.get("clickNum"))
    if not (all_clickNum and all_cost):
        return [0,0]
    ep_cost = round(all_exposureNum / all_cost,4)
    cost_click = round(all_cost / all_clickNum,4)
    # ep_cost = all_exposureNum / all_cost
    # cost_click = all_cost / all_clickNum
    return [ep_cost,cost_click]

def getBiddingData(shopid):
    #获取推广之前和推广之后的数据
    # headInfo中获取
    head_info_data = getHeadInfoData(shopid)
    # business_info中获取
    business_info = getBusinessInfo(shopid)
    #将所有的数据进行去重，以及进行格式上的统一
    #必须要有的数据有：每天的花费，当天的曝光，当天的访客数（以后需要的时候再进行获取，入店转化率，下单转化率等信息）
    busi_list = []
    head_list = []
    for b_info in business_info:
        if b_info.cost != 0:
            week = datetime.datetime.strptime(str(b_info.day), "%Y-%m-%d").weekday()
            busi_list.append({"cost":b_info.cost, "exposureNum": b_info.exposureNum, "clickNum": b_info.clickNum, "day": str(b_info.day), "week":week})
    for h_info in head_info_data:
        if h_info.headInfo:
            head_info = eval(h_info.headInfo)
            cost = float(head_info.get("cot").get("p"))
            exposureNum = int(head_info.get("ep").get("o"))
            clickNum = (head_info.get("ck").get("o"))
            if cost and exposureNum and clickNum:
                day = h_info.day
                week = datetime.datetime.strptime(str(day), "%Y-%m-%d").weekday()
                head_list.append({"cost":cost, "exposureNum": exposureNum, "clickNum": clickNum, "day": str(day), "week":week})
    return busi_list,head_list

def getBiddingsData(shopid):
    """
    获取竞价系统店铺的运营效果
    :param shopid:
    :return:
    """
    # 开始推广的时间
    date = str(getDate(shopid))
    # 获取推广的所有需要的数据
    busi_list, head_list = getBiddingData(shopid)
    # 对数据进行划分，分为智能推广之前的数据，以及智能推广之后的数据，先对busi_list的数据进行划分
    previous_list = []
    later_list = []
    for b_list in busi_list:
        if b_list.get("day") < date:
            previous_list.append(b_list)
        else:
            later_list.append(b_list)
    # 处理headInfo中的数据
    busi_list_lat_day = str(busi_list[-1].get("day"))
    for h_list in head_list:
        if h_list.get("day") > busi_list_lat_day:
            if h_list.get("day") < date:
                previous_list.append(h_list)
            else:
                later_list.append(h_list)
    # 获得数据之后，进行数据比对
    # for循环遍历智能推广的数据，并且获取准备数据分析需要的集合
    lenth_later_list = len(later_list)
    # 近七天以及近十天开始时间
    pre_start_time = datetime.datetime.strptime(str(date), "%Y-%m-%d")
    pre_start_time_strday = pre_start_time.strftime("%Y-%m-%d")
    # 近七天的数据的结束时间
    pre_end_seven_time = pre_start_time + datetime.timedelta(days=6)
    pre_end_seven_time_strday = pre_end_seven_time.strftime("%Y-%m-%d")
    # 近十天的数据的结束时间
    pre_end_ten_time = pre_start_time + datetime.timedelta(days=9)
    pre_end_ten_time_strday = pre_end_ten_time.strftime("%Y-%m-%d")
    # 智能推广的结束时间
    pre_lately_end_time = datetime.datetime.now()
    pre_lately_end_time_strday = pre_lately_end_time.strftime("%Y-%m-%d")
    # 智能推广后的七天的数据
    pre_lately_end_seven_time = pre_lately_end_time + datetime.timedelta(days=-6)
    pre_lately_end_seven_time_strday = pre_lately_end_seven_time.strftime("%Y-%m-%d")
    # 智能推广后的十天的数据
    pre_lately_end_ten_time = pre_lately_end_time + datetime.timedelta(days=-9)
    pre_lately_end_ten_time_strday = pre_lately_end_ten_time.strftime("%Y-%m-%d")
    # 当前自然周的数据
    week_now = datetime.datetime.now().weekday()
    # 自然周的数据的开始结束时间
    one_end_week_time = datetime.datetime.now()
    one_end_week_time_strday = one_end_week_time.strftime("%Y-%m-%d")
    one_start_week_time = one_end_week_time + datetime.timedelta(days=-int(week_now))
    one_start_week_time_strday = one_start_week_time.strftime("%Y-%m-%d")
    # now_week_day = []
    # for i in range(0,lenth_later_list):
    #     mid_week_day = later_list[lenth_later_list-i-1]
    #     now_week_day.append(mid_week_day)
    #     if mid_week_day.get("week")==0:
    #         break

    # 获取智能推广之前的数据，并且获取准备数据分析需要的集合
    lenth_pre_list = len(previous_list)
    # 计算最近七天的数据
    # 所有的开始时间
    start_one_time = (datetime.datetime.strptime(str(date), "%Y-%m-%d") + datetime.timedelta(days=-1))
    start_one_time_strday = start_one_time.strftime("%Y-%m-%d")
    # 第一个结束的时间
    end_seven_one_time = start_one_time + datetime.timedelta(days=-6)
    end_seven_one_time_strday = end_seven_one_time.strftime("%Y-%m-%d")
    # 第二个结束时间
    end_seven_two_time = end_seven_one_time + datetime.timedelta(days=-7)
    end_seven_two_time_strday = end_seven_two_time.strftime("%Y-%m-%d")
    # 第三个结束时间
    end_seven_three_time = end_seven_two_time + datetime.timedelta(days=-7)
    end_seven_three_time_strday = end_seven_three_time.strftime("%Y-%m-%d")
    # 第四个结束时间
    end_seven_four_time = end_seven_three_time + datetime.timedelta(days=-7)
    end_seven_four_time_strday = end_seven_four_time.strftime("%Y-%m-%d")
    # 十天类型的数据集合
    end_ten_one_time = start_one_time + datetime.timedelta(days=-9)
    end_ten_one_time_strday = end_ten_one_time.strftime("%Y-%m-%d")
    end_ten_two_time = end_seven_one_time + datetime.timedelta(days=-10)
    end_ten_two_time_strday = end_ten_two_time.strftime("%Y-%m-%d")
    end_ten_three_time = end_seven_two_time + datetime.timedelta(days=-10)
    end_ten_three_time_strday = end_ten_three_time.strftime("%Y-%m-%d")
    # 自然周数据获取
    pre_now_week_day = None
    for i in range(0, lenth_pre_list):
        num = previous_list[lenth_pre_list - i - 1].get("week")
        if num == week_now:
            pre_now_week_day = previous_list[lenth_pre_list - i - 1].get("day")
            break
    # 智能推广之前的第一个自然周的数据
    pre_start_one_week_time = datetime.datetime.strptime(str(pre_now_week_day), "%Y-%m-%d")
    pre_start_one_week_time_strday = pre_start_one_week_time.strftime("%Y-%m-%d")
    pre_end_one_week_time = pre_start_one_week_time + datetime.timedelta(days=-int(week_now))
    pre_end_one_week_time_strday = pre_end_one_week_time.strftime("%Y-%m-%d")
    # 智能推广之前的第二个自然周的数据
    pre_start_two_week_time = pre_start_one_week_time + datetime.timedelta(days=-7)
    pre_start_two_week_time_strday = pre_start_two_week_time.strftime("%Y-%m-%d")
    pre_end_two_week_time = pre_end_one_week_time + datetime.timedelta(days=-7)
    pre_end_two_week_time_strday = pre_end_two_week_time.strftime("%Y-%m-%d")
    # 智能推广之前的第三个自然周的数据
    pre_start_three_week_time = pre_start_two_week_time + datetime.timedelta(days=-7)
    pre_start_three_week_time_strday = pre_start_three_week_time.strftime("%Y-%m-%d")
    pre_end_three_week_time = pre_end_two_week_time + datetime.timedelta(days=-7)
    pre_end_three_week_time_strday = pre_end_three_week_time.strftime("%Y-%m-%d")
    # 智能推广之前的第二个自然周的数据
    pre_start_four_week_time = pre_start_three_week_time + datetime.timedelta(days=-7)
    pre_start_four_week_time_strday = pre_start_four_week_time.strftime("%Y-%m-%d")
    pre_end_four_week_time = pre_end_three_week_time + datetime.timedelta(days=-7)
    pre_end_four_week_time_strday = pre_end_four_week_time.strftime("%Y-%m-%d")

    # 先前数据的所有维度的列表
    # 七天的四个列表
    one_seven_day_list = []
    two_seven_day_list = []
    three_seven_day_list = []
    four_seven_day_list = []
    # 十天的四个列表
    one_ten_day_list = []
    two_ten_day_list = []
    three_ten_day_list = []
    four_ten_day_list = []
    # 四个自然周的数据
    one_week_day_list = []
    two_week_day_list = []
    three_week_day_list = []
    four_week_day_list = []
    for pre in previous_list:
        pre_day = str(pre.get("day"))
        # 一七天
        if pre_day >= end_seven_one_time_strday and pre_day <= start_one_time_strday:
            one_seven_day_list.append(pre)
        # 二七天
        if pre_day >= end_seven_two_time_strday and pre_day <= start_one_time_strday:
            two_seven_day_list.append(pre)
        # 三七天
        if pre_day >= end_seven_three_time_strday and pre_day <= start_one_time_strday:
            three_seven_day_list.append(pre)
        # 四七天
        if pre_day >= end_seven_four_time_strday and pre_day <= start_one_time_strday:
            four_seven_day_list.append(pre)
            # 一十天
        if pre_day >= end_ten_one_time_strday and pre_day <= start_one_time_strday:
            one_ten_day_list.append(pre)
            # 二十天
        if pre_day >= end_ten_two_time_strday and pre_day <= start_one_time_strday:
            two_ten_day_list.append(pre)
            # 三十天
        if pre_day >= end_ten_three_time_strday and pre_day <= start_one_time_strday:
            three_ten_day_list.append(pre)
        # 第一个自然周
        if pre_day >= pre_end_one_week_time_strday and pre_day <= pre_start_one_week_time_strday:
            one_week_day_list.append(pre)
        # 第二个自然周
        if pre_day >= pre_end_two_week_time_strday and pre_day <= pre_start_two_week_time_strday:
            two_week_day_list.append(pre)
        # 第三个自然周
        if pre_day >= pre_end_three_week_time_strday and pre_day <= pre_start_three_week_time_strday:
            three_week_day_list.append(pre)
        # 第四个自然周
        if pre_day >= pre_end_four_week_time_strday and pre_day <= pre_start_four_week_time_strday:
            four_week_day_list.append(pre)

    # 智能推广之后的数据
    # 近七天的列表
    later_last_seven_list = []
    # 开始七天的列表
    later_begin_seven_list = []
    # 近十天的列表
    later_last_ten_list = []
    # 开始十天的列表
    later_begin_ten_list = []
    # 自然周的列表
    later_week_list = []
    for lat in later_list:
        later_day = str(lat.get("day"))
        # 近七天的列表
        if later_day >= pre_start_time_strday and later_day <= pre_end_seven_time_strday:
            later_last_seven_list.append(lat)
        # 开始七天的列表
        if later_day >= pre_lately_end_seven_time_strday  and later_day <= pre_lately_end_time_strday:
            later_begin_seven_list.append(lat)
        # 近十天的列表
        if later_day >= pre_start_time_strday and later_day <= pre_end_ten_time_strday:
            later_last_ten_list.append(lat)
        # 开始十天的列表
        if later_day >= pre_lately_end_ten_time_strday and later_day <= pre_lately_end_time_strday:
            later_begin_ten_list.append(lat)
        # 自然周的列表
        if later_day <= one_end_week_time_strday and later_day >= one_start_week_time_strday:
            later_week_list.append(lat)

    # 先前数据的所有维度的列表
    # 七天的四个列表
    one_seven_day_list_result = getAvgByList(one_seven_day_list)
    two_seven_day_list_result = getAvgByList(two_seven_day_list)
    three_seven_day_list_result = getAvgByList(three_seven_day_list)
    four_seven_day_list_result = getAvgByList(four_seven_day_list)
    # 十天的四个列表
    one_ten_day_list_result = getAvgByList(one_ten_day_list)
    two_ten_day_list_result = getAvgByList(two_ten_day_list)
    three_ten_day_list_result = getAvgByList(three_ten_day_list)
    four_ten_day_list_result = getAvgByList(four_ten_day_list)
    # 四个自然周的数据
    one_week_day_list_result = getAvgByList(one_week_day_list)
    two_week_day_list_result = getAvgByList(two_week_day_list)
    three_week_day_list_result = getAvgByList(three_week_day_list)
    four_week_day_list_result = getAvgByList(four_week_day_list)

    # 智能推广之后的数据
    # 近七天的列表
    later_last_seven_list_result = getAvgByList(later_last_seven_list)
    # 开始七天的列表
    later_begin_seven_list_result = getAvgByList(later_begin_seven_list)
    # 近十天的列表
    later_last_ten_list_result = getAvgByList(later_last_ten_list)
    # 开始十天的列表
    later_begin_ten_list_result = getAvgByList(later_begin_ten_list)
    # 自然周的列表
    later_week_list_result = getAvgByList(later_week_list)

    # 二十种对比情况，排列组合依次列出，数据格式为{"later":[] ,"pre":[], "cha":[]}
    back_data = [{"later": later_last_seven_list_result, "pre": one_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - one_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第一个七天对比"},
                 {"later": later_last_seven_list_result, "pre": two_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - two_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第二个七天对比"},
                 {"later": later_last_seven_list_result, "pre": three_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - three_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第三个七天对比"},
                 {"later": later_last_seven_list_result, "pre": four_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - four_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第四个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": one_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - one_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第一个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": two_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - two_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第二个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": three_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - three_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第三个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": four_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - four_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第四个七天对比"},
                 {"later": later_last_ten_list_result, "pre": one_ten_day_list_result,
                  "cha": [later_last_ten_list_result[i] - one_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "近十天和第一个十天对比"},
                 {"later": later_last_ten_list_result, "pre": two_ten_day_list_result,
                  "cha": [later_last_ten_list_result[i] - two_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "近十天和第二个十天对比"},
                 {"later": later_last_ten_list_result, "pre": three_ten_day_list_result,
                  "cha": [later_last_ten_list_result[i] - three_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "近十天和第三个十天对比"},
                 {"later": later_begin_ten_list_result, "pre": one_ten_day_list_result,
                  "cha": [later_begin_ten_list_result[i] - one_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "开始十天和第一个十天对比"},
                 {"later": later_begin_ten_list_result, "pre": two_ten_day_list_result,
                  "cha": [later_begin_ten_list_result[i] - two_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "开始十天和第二个十天对比"},
                 {"later": later_begin_ten_list_result, "pre": three_ten_day_list_result,
                  "cha": [later_begin_ten_list_result[i] - three_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "开始十天和第三个十天对比"},
                 {"later": later_week_list_result, "pre": one_week_day_list_result,
                  "cha": [later_week_list_result[i] - one_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第一个自然周比较"},
                 {"later": later_week_list_result, "pre": two_week_day_list_result,
                  "cha": [later_week_list_result[i] - two_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第二个自然周比较"},
                 {"later": later_week_list_result, "pre": three_week_day_list_result,
                  "cha": [later_week_list_result[i] - three_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第三个自然周比较"},
                 {"later": later_week_list_result, "pre": four_week_day_list_result,
                  "cha": [later_week_list_result[i] - four_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第四个自然周比较"}, ]
    return back_data

def bindShopAccount(account,userName, type):
    """
    将用户绑定账号密码
    :param account:
    :param shopAccount:
    :param type:
    :return:
    """
    shop = None
    session = Session()
    try:
        if type == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
        if shop:
            shop.userName = userName
            session.commit()
            session.close()
            return True
        else:
            session.close()
            return False
    except:
        session.rollback()
        session.close()
        return False

